package com.wmlive.hhvideo.heihei.bells.presenter;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.base.BasePresenter;
import com.wmlive.hhvideo.common.network.HttpConstant;
import com.wmlive.hhvideo.heihei.beans.main.Author;
import com.wmlive.hhvideo.heihei.beans.splash.InitCatchData;
import com.wmlive.hhvideo.heihei.bells.view.FollowView;
import com.wmlive.hhvideo.heihei.db.datatable.IMMessageUserTable;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageUserDBManager;
import com.wmlive.networklib.entity.BaseResponse;
import com.wmlive.networklib.entity.DCNetObserver;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by vhawk on 2017/7/6.
 */

public class FollowPresenter extends BasePresenter<FollowView> {

    public FollowPresenter(FollowView view) {
        super(view);
    }

    /**
     * 关注用户
     *
     * @param userId
     * @param position
     * @param messageId
     */
    public void followUser(long userId, final int position, final String messageId) {

        if (userId <= 0) {
            return;
        }

        String url = InitCatchData.userFollowUser();
        if (!TextUtils.isEmpty(url)) {
            executeRequest(HttpConstant.TYPE_BELL_FOLLOW_USER, getHttpApi().followAnchor(url, userId))
                    .subscribe(new DCNetObserver<BaseResponse>() {
                        @Override
                        public void onRequestDataReady(int requestCode, String message, BaseResponse response) {
                            if (null != viewCallback) {
                                updataFollowStatus(messageId, true);
                                viewCallback.handleFollowSucceed(position);
                            }
                        }

                        @Override
                        public void onRequestDataError(int requestCode, int serverCode, String message) {
                            if (null != viewCallback) {
                                viewCallback.handleFollowFailure(message);
                            }
                        }
                    });
        } else if (null != viewCallback) {
            viewCallback.handleNetError();
        }
    }

    /**
     * 取消关注用户
     *
     * @param userId
     * @param position
     * @param messageId
     */
    public void unFollowUser(long userId, final int position, final String messageId) {

        if (userId <= 0) {
            return;
        }

        String url = InitCatchData.userUnFollowUsr();

        if (!TextUtils.isEmpty(url)) {
            executeRequest(HttpConstant.TYPE_BELL_UNFOLLOW_USER, getHttpApi().updateFollowerState(url, userId))
                    .subscribe(new DCNetObserver<BaseResponse>() {
                        @Override
                        public void onRequestDataReady(int requestCode, String message, BaseResponse response) {
                            if (null != viewCallback) {
                                updataFollowStatus(messageId, false);
                                viewCallback.handleUnFollowSucceed(position);
                            }
                        }

                        @Override
                        public void onRequestDataError(int requestCode, int serverCode, String message) {
                            if (null != viewCallback) {
                                viewCallback.handleUnFollowFailure(message);
                            }
                        }
                    });
        } else if (null != viewCallback) {
            viewCallback.handleNetError();
        }
    }

    /**
     * 更新关注状态数据
     *
     * @param messageId
     * @param isFollow
     */
    private void updataFollowStatus(final String messageId, final boolean isFollow) {


        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Object>() {
                    @Override
                    public Object apply(@NonNull Integer integer) throws Exception {
                        IMMessageUserDBManager userDBManager = IMMessageUserDBManager.getInstance(DCApplication.getDCApp());
                        IMMessageUserTable userTable = userDBManager.getIMUserEntryByMsgId(messageId);
                        if (userTable != null){
                            Author fromUser = new Gson().fromJson(userTable.getFrom_user(), Author.class);
                            fromUser.getRelation().setIs_follow(isFollow);
                            userTable.setFrom_user(new Gson().toJson(fromUser));
                            userDBManager.updateIMUserDataByEntry(userTable);
                        }
                        return 0;
                    }
                }).subscribe();

    }
}
